package org.dynamicallyacquired.kafka.listener;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.soboys.restapispringbootstarter.Result;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.dynamicallyacquired.domain.AndroidInfo;
import org.dynamicallyacquired.request.BusinessException;
import org.dynamicallyacquired.request.HttpStatus;
import org.dynamicallyacquired.service.IAndroidInfoService;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


@Component
public class SimpleListener {
    @Resource
    private IAndroidInfoService androidInfoService;

    @Resource
    private JavaMailSender mailSender;

    private void sendEmailToAdmin() {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("1905333495@qq.com");
        message.setTo("1905333495@qq.com");
        message.setSubject("Kafka消费者错误");
        message.setText("消费者在处理消息时遇到重复错误，超过了阈值。请检查系统。");
        mailSender.send(message);
    }

    @KafkaListener(topics = "android",groupId = "android")
    public void listen1(AndroidInfo data,Acknowledgment acknowledge) {
        System.out.println("打包完成，返回数据：-->>"+data);
        System.out.println("开始生成二维码以及url");
        try {
            String qr = data.getFullPath()+"/qrcode.jpg";
            String jksQr = data.getFullPath()+"/jksQr.jpg";
            String url = "http://download.free.idcfengye.com/" + data.getApkPath();
            String jksUrl = "http://download.free.idcfengye.com/" + "apk/jks/"+data.getAppName()+".jks";
            QrConfig config = new QrConfig();
            config.setErrorCorrection(ErrorCorrectionLevel.H);
            File generate = QrCodeUtil.generate(url, /*QrConfig.create().setImg("e:/logo_small.jpg"),*/300,300, FileUtil.file(qr));
            File generateJks = QrCodeUtil.generate(jksUrl, /*QrConfig.create().setImg("e:/logo_small.jpg"),*/300,300, FileUtil.file(jksQr));
            System.out.println("生成 二维码：-->>"+ qr);
            System.out.println("apk路径：-->>"+ generate.toString());
            System.out.println("生成 apk下载url：-->>"+ url);
            System.out.println("jks路径：-->>"+ generateJks.toString());
            System.out.println("生成 jks密钥下载url：-->>"+ jksUrl);
            data.setDownloadUrl(url);
            data.setIsPackage(1);
            System.out.println(data);
            androidInfoService.update(data,new EntityWrapper<AndroidInfo>().eq("uuid",data.getUuid()));
            acknowledge.acknowledge();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private final Lock lock = new ReentrantLock();
    private static int failureCount = 0;
    private static final int FAILURE_THRESHOLD = 10;
    @KafkaListener(topics = "android_generate",groupId = "android_generate")
    public void listen2(String data,Acknowledgment acknowledge) {
        lock.lock();
        try  {
            System.out.println("开始查询命令uuid: -->> " + data);
            AndroidInfo androidInfo = androidInfoService.selectOne(new EntityWrapper<AndroidInfo>().eq("uuid", data));
            if (androidInfo.getIsPackage() == 1){
                throw new BusinessException(HttpStatus.INVALID_Android.getMessage(),HttpStatus.INVALID_Android.getCode());
            }
            System.out.println("查询到: -->> " + androidInfo);
            System.out.println("开始执行生成key的命令: " + androidInfo);
            String path = "C:\\Users\\LT02\\Desktop\\apk\\jks"+"\\"+androidInfo.getAppName().trim()+".jks";
            File file = new File(path);

            if (file.exists()) {
                System.out.println("文件已存在: " + path);
            } else {
                System.out.println("文件不存在，将创建: " + path);
                generateKeyStore(path, androidInfo.getPackageName());
            }
            System.out.println("开始执行打包的命令: userId-->>" + data);
            ProcessBuilder builder = new ProcessBuilder("cmd", "/c", "gradlew.bat", "assembleRelease",
                    "-Pandroid.injected.signing.store.file=" + path,
                    "-Pandroid.injected.signing.store.password=" + androidInfo.getPackageName(),
                    "-Pandroid.injected.signing.key.alias=" + androidInfo.getPackageName(),
                    "-Pandroid.injected.signing.key.password=" + androidInfo.getPackageName(),
                    "-PUUID=" + data);
            builder.directory(new File("D:\\software\\Dynamicallyacquired"));
//            builder.directory(new File("C:\\Users\\LT08\\Desktop\\Dynamicallyacquired"));
            builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
            builder.redirectError(ProcessBuilder.Redirect.INHERIT);

            Process process = builder.start();
            int exitCode = process.waitFor();
            System.out.println("Process exited with code: " + exitCode);
            if (exitCode==0){
                acknowledge.acknowledge();
            }else {
                failureCount++;
                if (failureCount >= FAILURE_THRESHOLD) {

                    failureCount = 0;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            sendEmailToAdmin();
                        }
                    }).start();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            acknowledge.acknowledge();
        } finally {
            lock.unlock();
        }
    }

    private void generateKeyStore(String keystorePath,String keypass) throws IOException, InterruptedException {
        List<String> command = Arrays.asList(
                "keytool", "-genkeypair", "-v",
                "-keystore", keystorePath,
                "-alias", keypass,
                "-keyalg", "RSA", "-keysize", "2048", "-validity", "10000",
                "-storepass", keypass, "-keypass", keypass,
                "-dname", String.format("CN=%s, OU=%s, O=%s, L=%s, S=%s, C=%s", keypass, keypass, keypass, keypass, keypass, "US")
        );

        ProcessBuilder builder = new ProcessBuilder(command);
        builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        builder.redirectError(ProcessBuilder.Redirect.INHERIT);
        Process process = builder.start();
        int exitCode = process.waitFor();

        if (exitCode != 0) {
            throw new RuntimeException("Failed to generate keystore");
        }
    }

}
